package com.example.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.usercenter.model.domain.User;
import com.example.usercenter.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热任务
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private RedissonClient redissonClient;
    //重点用户
    private List<Long> mainUserList= Arrays.asList(1l);
    //可以用这个注解指定周期，多久执行一次
//    @EnableScheduling 需要开启注解在Application里面
    //每天执行，预热推荐用户
    @Scheduled(cron = "0 31 * * * *")
    public void doCacheRecommendUser(){
        RLock lock=redissonClient.getLock("pq:precachejob:docache:lock");
        try {
            //只有一个线程能获取到锁
            // 0相当于在这里等锁的等待时间，30000L过期时间
            if(lock.tryLock(0,-1, TimeUnit.MICROSECONDS)){
                for (Long userId:mainUserList){
                    QueryWrapper<User> queryWrapper=new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1,20),queryWrapper);
                    String redisKey=String.format("pq:user:recommend::%s",userId);
                    ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
                    //写缓存
                    try {
                        valueOperations.set(redisKey,userPage);
                    } catch (Exception e) {
                        log.error("redis set key error",e,30000, TimeUnit.MICROSECONDS);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error",e);
        }finally {
            //只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }


    }
}
